package com.jgc.stage02.同步工具类;

import java.util.concurrent.Exchanger;

/**
 * Created by Administrator on 2022/2/11.
 * Exchanger类可用于两个线程之间交换信息。
 * 可简单地将Exchanger对象理解为一个包含两个格子的容器，通过exchanger方法可以向两个格子中填充信息
 * 当两个格子中的均被填充时，该对象会自动将两个格子的信息交换，然后返回给线程，从而实现两个线程的信息交换
 */
public class TestExchanger extends Thread{
    private Exchanger<String> exchanger;
    private String string;
    private String threadName;

    public TestExchanger(Exchanger<String> exchanger, String string,
                         String threadName) {
        this.exchanger = exchanger;
        this.string = string;
        this.threadName = threadName;
    }
    public void run() {
        try {
            System.out.println(threadName + ": " + exchanger.exchange(string));
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        TestExchanger test1 = new TestExchanger(exchanger, "string1", "thread-1");
        TestExchanger test2 = new TestExchanger(exchanger,"string2","thread-2");
        test1.start();
        test2.start();
    }
}
